import React, {  useRef,useEffect ,useState,forwardRef,useImperativeHandle,FC} from 'react'
import { Button, Input,Form,Spin,Modal, Select} from 'antd'
import MyTable from '@/components/common/table'
// import { isAuthorized } from '@/assets/js/publicFunc'
import MySelect from '@/components/common/mySelect'
import User from '@/api/user'
import { formItemLayout } from '@/config/layout'
import './index.less';
import Role from '@/api/role'
import ChooseUserCom from '@/components/common/chooseUser/index'

const AuthList: FC = () => {
  const tableRef: RefType = useRef()
  // const history = useHistory()
  const AuthEditRef: RefType = useRef()
  
  // 添加
  const add = () => {
    AuthEditRef.current.init('');
  }
  // // 编辑
  // const edit = (record) => {
  //   AuthEditRef.current.init(record.userid,record);
  // }
   // 删除
   const del = (record:any) => {
    Modal.confirm({
      title: '确认删除？',
      
      onOk() {
        User.userGrantDel({
          staffid :record.staffId,
        }).then(()=>{
          tableRef.current.update();
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  // //分配权限
  // const auth = () => {
  //   history.push('/sys/auth/auth?id=666')
  // }
  // 新增按钮
  const AddBtn = () => (
    <Button className="fr" onClick={add} type="primary">
      新增权限用户
    </Button>
  )

 
 
  const columns = [
    {
      title: '用户名',
      dataIndex: 'staffName',
      key:'staffName',
      render: (txt)=>{
        return txt
      }
    },
    {
      title: '角色',
      dataIndex: 'sysRoles',
      key:'sysRoles',
      render: (txt,record)=>{
        let sysRoles = record['sysRoles']?record['sysRoles']:[];
        let names = '';
        sysRoles.map((e,i)=>{
          if(i!==0){
            names+='、'
          }
          names+= e['rolename'];
          return 1
        })
        return names
      }
    },
    {
      title: '操作',
      dataIndex: 'operations',
      align: 'center',
      width:150,
      render: (txt,record) => (
        <>
          <Button className="btn" onClick={()=>{
            del(record);
          }} size="small">
            删除
          </Button>
        </>
      )
    }
  ]
  return (
    <>  
      <div style={{marginBottom:'10px',overflow:'hidden'}}>
        <AddBtn />
      </div>
      
      <MyTable
        expendParams={{'hasrole':true}}
        apiFun={User.getList}
        columns={columns}
        ref={tableRef}
        extraProps={{ results: 10 }}
      />
      <AuthEditCom ref={AuthEditRef} callback={()=>{
        tableRef.current.update();
      }}/>
      
    </>
  )
}
export default AuthList





//新建/修改人员权限
const AuthEdit = (props,refs) => {
  const [loading, setLoading] = useState<boolean>(false)
  const ChooseUserRef: RefType = useRef()
  //显示隐藏弹窗
  const [isModalVisible, setIsModalVisible] = useState(false);
  //角色列表
  const [roleList,setRolelist] = useState([]);
   //nowid
   const [nowId,setNowId] = useState('');
   //
   const [nowCheckedUser,setnowCheckedUser] = useState({});
   //form
   const [form] = Form.useForm()
   const { setFieldsValue } = form
   useImperativeHandle(refs, () => ({
    init: (id) => {
      setNowId(id);
      setFieldsValue({
        roleids:[],
      });
      showModal();
     
    }
  }))
  const getRoleList = ()=>{
    Role.getList({pageSize:10000}).then((res)=>{
      let list = res['data']['list'];
      list.map((e,i)=>{
        list[i]['name'] = e['rolename'];
        list[i]['key'] = e['roleid'];
        return 1
      })
      setRolelist(list);
    })
  }
  useEffect(()=>{
    getRoleList();
  },[])
  //显示弹窗
  const showModal = () => {
    setIsModalVisible(true);
  };
  //确定
  const handleOk = () => {
    form.validateFields().then((vals) => {
      if(nowId){
        console.log(nowId);
      }
      const Obj = form.getFieldsValue()
      setLoading(true)

      const fn = User.userGrant;
      const params = {
        staffid:nowCheckedUser['id'],
        roleids:Obj['roleids']
      };
      fn(params).then((res)=>{
        handleCancel();
      })
    }).catch(info => {
      
    })
  };
  //取消
  const handleCancel = () => {
    setIsModalVisible(false);
    setLoading(false);
    setNowId('');
    setnowCheckedUser({});
    props.callback&&props.callback();
  };
  return <Modal 
    title={'分配权限'}
    visible={isModalVisible} 
    onOk={handleOk} 
    onCancel={handleCancel}
    width={600}
    maskClosable={false}
    >

    <Spin spinning={loading}>
      <Form {...formItemLayout} form={form}>
        <Form.Item
          label="选择人员"
        >
          <div className="chooseUserWrap" onClick={()=>{
            ChooseUserRef.current.init();
          }}>
             <Input value={nowCheckedUser['name']} />
          </div>
        </Form.Item>
        
        <Form.Item
          label="角色"
          name="roleids"
          rules={[
            {
              required: true,
              message: '请输入角色'
            }
          ]}
        >
          <Select
            placeholder="请选择角色"
            mode="multiple"
          >
            {
              roleList.map((item,i)=>{
                return <Select.Option key={item.key} title={item.name} value={item.key}>
                  {item.name}
                </Select.Option>
              })
            }
          </Select>
        </Form.Item>
        
        
      </Form>
      <ChooseUserCom ref={ChooseUserRef} callback={(callback_v)=>{
          let obj = callback_v[0];
          setnowCheckedUser(obj)
      }}/>
    </Spin>
     
  </Modal>
}



const AuthEditCom = forwardRef(AuthEdit);